<?php

/**
 * 工作账号
 * @author HelloWorld
 * UTF-8
 */
class WorkernumberController extends Controller_Base
{

    public function indexAction()
    {
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $line = intval($request->getQuery('line', 1));
        $mediator = ($request->getQuery('mediator', ''));
        $limit = intval($request->getQuery('limit', 10));
        $mediationOrganId= trim($this->getRequest()->getQuery('mediationOrganId', 0));
        $page = $page ? $page : 1;
        $start = ($page - 1) * $limit;

        $query = array('limit' => $limit, 'page' => $page);

        $where = $this->getWhere();
        array_push($where, "isDel=1","line={$line}");
        if($mediator){
            array_push($where, "mediator='{$mediator}'");
            $query['mediator'] = $mediator;
        }
        $query['mediationOrganId'] = $mediationOrganId;
        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => $start,
            'order' => 'workerId'
        );
        $list = Module_Mediate_Workernumber::getInstance()->getAllBySearch(array("*"), $seacher, true);
        $total = Module_Mediate_Workernumber::getInstance()->getAllBySearch(array("count(*) as num"), ['where' => $seacher['where']], true);
        $total = $total[0]['num'];
        $totalPage = ceil($total / $limit);
        $this->getMediator();
        $this->getMediationOrgan();
        SmartyAdapter::assign('arrList', $list);
        SmartyAdapter::assign('callNum', Module_Mediate_Workernumber::$callNum[$line]);
        SmartyAdapter::assign('numCard', Module_Mediate_Workernumber::$numCard);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('line', $line);

        SmartyAdapter::assign('page_query', http_build_query($query));
    }
    //同步坐席   无用了
    public function syncAction_back()
    {
        $delete = [];
        $res = Module_CallCenter_ZhonTou_Worker::getInstance()->getWoker();
        if (!empty($res) && $res['code'] == 200 && !empty($res['data']) && count($res['data']) > 0) {
            $syncListArr = $res['data'];
            $superWorker = array_search(true,array_column($syncListArr,'superWorker','workerId'));
            $syncListArr = array_column($syncListArr, null, 'workerId');
            //去除超管坐席
            unset($syncListArr[$superWorker]);
            $syncList = array_keys($syncListArr);
            $list = Module_Mediate_Workernumber::getInstance()->getAllBySearch([], ["where" => ["isDel=1"]]);
            if (!empty($list)) {
                $list = array_column($list, 'workerId');
                $insert = array_diff($syncList, $list);
                $update = array_intersect($syncList,$list);
                $delete = array_diff($list, $syncList);
            } else {
                $insert = $syncList;
            }
            if (!empty($insert)) {
                foreach ($insert as $k => $v) {
                    $arr = [
                        'workerId' => $syncListArr[$v]['workerId'],
                        'extnumber' => $syncListArr[$v]['extnumber'],
                        'extnumberPswd' => $syncListArr[$v]['extnumberPswd'],
                        'isDel' => 1,
                    ];
                    Module_Mediate_Workernumber::getInstance()->singleInsert($arr);
                }
            }

            if (!empty($delete)) {
                foreach ($delete as $key => $val) {
                    Module_Mediate_Workernumber::getInstance()->singleUpdate(['isDel' => 2, 'workerId' => $val], 'workerId');
                }
            }
        }


        AjaxTool::returnJsonData(200, '操作成功');

    }
    //同步坐席
    public function syncAction()
    {
        $line = $this->getRequest()->getPost('line', 1);
        $res = Module_CallCenter_YunKeFu_Call::getInstance($line)->queryQueue($line);
        if($line == 1){
            $sys_admin = Module_User_Administrator::getInstance()->getAllBySearch([],['where'=>['workerId>0']]);
            $sys_worker = array_column($sys_admin,null,'workerId');
        }else{
            $sys_admin = Module_User_Administrator::getInstance()->getAllBySearch([],['where'=>['workerId2>0']]);
            $sys_worker = array_column($sys_admin,null,'workerId2');
        }
        if (!empty($res) && $res['code'] == 200 && !empty($res['data']) && count($res['data']) > 0) {
            $sync_workes = [];
            foreach ($res['data'] as $data){
                if(!empty($data['AssignMembers'])){
                    foreach ($data['AssignMembers'] as $agent){
                        $sync_workes[$agent['agentExten']] = [
                            'accountId' =>$data['Exten'],
                            'displayName' =>$data['DisplayName'],
                            'workerId'=>$agent['agentExten']
                        ];
                    }
                }

            }

            $sync_workerId = array_keys($sync_workes);
            $list = Module_Mediate_Workernumber::getInstance()->getAllBySearch([], ["where" => ["isDel=1","line={$line}"]]);
            if (!empty($list)) {
                $db_workers = array_column($list, null,'workerId');
                $db_workerId= array_column($list, 'workerId');
                $insert = array_diff($sync_workerId, $db_workerId);
                $update = array_intersect($sync_workerId,$db_workerId);
                $delete = array_diff($db_workerId, $sync_workerId);
            } else {
                $insert = $sync_workerId;
            }
            if (!empty($insert)) {
                foreach ($insert as $k => $v) {
                    $arr = [
                        'workerId' => $sync_workes[$v]['workerId'],
                        'extnumber' => $sync_workes[$v]['workerId'],
                        'extnumberPswd' => '',
                        'accountId' => $sync_workes[$v]['accountId'],
                        'displayName' => $sync_workes[$v]['displayName'],
                        'mediatorId' => empty($sys_worker[$sync_workes[$v]['workerId']]) ? 0 : $sys_worker[$sync_workes[$v]['workerId']]['id'],
                        'mediator' => empty($sys_worker[$sync_workes[$v]['workerId']]) ? '' : $sys_worker[$sync_workes[$v]['workerId']]['name'],
                        'mediationOrganId' => empty($sys_worker[$sync_workes[$v]['workerId']]) ? 0 : $sys_worker[$sync_workes[$v]['workerId']]['name'],
                        'isDel' => 1,
                        'line' => $line,
                    ];
                    Module_Mediate_Workernumber::getInstance()->singleInsert($arr);
                }
            }
            if (!empty($update)) {
                foreach ($update as $k => $v) {
                    if($sync_workes[$v]['accountId'] != $db_workers['workerId']['accountId'] || $sync_workes[$v]['displayName'] != $db_workers['workerId']['displayName']){
                        Module_Mediate_Workernumber::getInstance()->singleUpdate([
                            'accountId' => $sync_workes[$v]['accountId'],
                            'displayName'=>$sync_workes[$v]['displayName'],
                            'workerId' => $v,
                            'mediatorId' => empty($sys_worker[$v]) ? 0 : $sys_worker[$v]['id'],
                            'mediator' => empty($sys_worker[$v]) ? '' : $sys_worker[$v]['name'],
                            'mediationOrganId' => empty($sys_worker[$v]) ? 0 : $sys_worker[$v]['mediationOrganId'],

                        ],
                            'workerId');
                    }
                }
            }

            if (!empty($delete)) {
                foreach ($delete as $k => $v) {
                    Module_Mediate_Workernumber::getInstance()->singleUpdate(['isDel' => 2, 'workerId' => $v], 'workerId');

                }
            }
        }else{
            AjaxTool::returnJsonData(400, $res['message']);

        }
        AjaxTool::returnJsonData(200, '操作成功');

    }

    public function addAction(){

        if ($this->getRequest()->getPost()) {
            $data = $this->getRequest()->getPost('data', '');
            parse_str(urldecode($data),$data);
            //单个添加
            if(!empty($data['workerId'])){
                if(empty($data['extnumber']) || empty($data['outNumber']) || empty($data['extnumberPswd'])){
                    AjaxTool::returnJsonData(400,'请填完整数据');
                }

                if(strlen($data['extnumberPswd'])<6){
                    AjaxTool::returnJsonData(400,'分机密码不能少于6个字符');
                }
                $history=  Module_Mediate_Workernumber::getInstance()->getOne(['id'],["workerId={$data['workerId']}"],true);
                if($history){
                    AjaxTool::returnJsonData(400,'该话机已经存在');
                }
                $res = [

                    'workerId' => $data['workerId'],
                    'extnumber' => $data['extnumber'],
                    'outNumber' => $data['outNumber'],
                    'extnumberPswd' => $data['extnumberPswd'],
                    'isDel' => 1,
                ];
                try{
                    $insert_res=  Module_Mediate_Workernumber::getInstance()->singleInsert($res);
                    if(!$insert_res){
                        AjaxTool::returnJsonData(400, "操作失败");
                    }
                }catch (Exception $e){
                    AjaxTool::returnJsonData(400, $e->getMessage());
                }

            }

            //批量导入
            $file = $this->getRequest()->getFiles('file');
//            if ($file['error'] == 4) {
//                AjaxTool::returnJsonData(404,'请上传文件');
//            }
            if(!empty($file)){
                $img_url = '';
                if ($file['error'] != 4) {
                    $uploadFile = Lib_Upload::getInstance()->uploadFile($file, 'caseupload');
                    if (!$uploadFile || $uploadFile['code']) {
                        AjaxTool::returnJsonData(405,'上传失败');
                    }
                    $img_url = $uploadFile['data'];
                }
                //$img_url = '/2023-04-25.xlsx';
                $file_path=  '/resource' . $img_url;
                $url = realpath(LIBRARY_DIR . '/../') . '/resource' . $img_url;
                $file_info = pathinfo($url);
                if ($file_info && strtolower($file_info['extension']) == 'csv') {
                    $res = array_map('str_getcsv', file($url));
                    if ($res) {
                        unset($res[0]);
                    }
                } else {
                    try {
                        $res = Lib_XlsxRead::getInstance()->execute($url,1);
                    } catch (Exception $e) {
                        AjaxTool::returnJsonData(406,'文件格式不对'.$e);
                    }
                    if (empty($res)) {
                        AjaxTool::returnJsonData(407,'未发现数据');
                    }
                }
//                Func_Log::write("test11", '$res' , var_export($res, true));
                $header = $res[1];
                unset($res[1]);
                if (!$res) {
                    AjaxTool::returnJsonData(408, "未发现数据");
                }
                if(empty($header)){
                    AjaxTool::returnJsonData(409, "未发现表格表头");
                }
                if (!empty($res)) {
                    $success = 0;
                    $fail = 0;
                    foreach ($res as $k => $v) {
                        if(empty($v[0]) || empty($v[1]) || empty($v[2]) || empty($v[3])){
                            $fail ++;
                            continue;
                        }
                        if(strlen($v[3])<6){
                            $fail ++;
                            continue;
                        }
                        $history=  Module_Mediate_Workernumber::getInstance()->getOne(['id'],["workerId={$v[0]}",'isDel = 1'],true);
                        if($history){
                            $fail ++;
                            continue;
                        }
                        $arr = [
                            'workerId' => $v[0],
                            'extnumber' => $v[1],
                            'outNumber' => $v[2],
                            'extnumberPswd' => $v[3],
                            'isDel' => 1,
                        ];
                        try {
                            $res = Module_Mediate_Workernumber::getInstance()->singleInsert($arr);
                            if ($res){
                                $success++;
                                continue;
                            }else{
                                $fail ++;
                                continue;
                            }
                        } catch (Exception $e) {
                            $fail ++;
                            continue;
                        }
                    }
                }
                AjaxTool::returnJsonData(200, "成功添加 {$success}个,失败 {$fail}个");

            }
        }
        if(empty($res)){
            AjaxTool::returnJsonData(500, "未检测到添加数据");
        }
        AjaxTool::returnJsonData(200, "操作成功");
    }


    public function delAction(){

        $ids = $this->getRequest()->getPost('ids', '');
        if(empty($ids)){
            AjaxTool::returnJsonData(400, "请选择数据");
        }
        $idArr =  explode(",",$ids);
        if(!empty($idArr)){
           $res =  Module_Mediate_Workernumber::getInstance()->getAllBySearch([],["where"=>['id in ('.$ids.')']],false);

           foreach ($res as $k=>$v){
                if(!empty($v['mediatorId'])){
                    AjaxTool::returnJsonData(400, "坐席号{$v['workerId']}未解除绑定,批量删除失败!");
                }
            }
            foreach ($idArr as $k=>$v){
                Module_Mediate_Workernumber::getInstance()->singleUpdate(['isDel' => 2, 'id' => $v]);
            }

        }

        AjaxTool::returnJsonData(200, "操作成功");
    }
    public function bindCallNumAction(){

        $ids = $this->getRequest()->getPost('ids', '');
        $callNum = $this->getRequest()->getPost('callNum', '');
        if(empty($ids)){
            AjaxTool::returnJsonData(400, "请选择数据");
        }
        if(empty($callNum)){
            AjaxTool::returnJsonData(400, "请选择绑定外显号码");
        }
        if(!in_array($callNum,array_keys(Module_Mediate_Workernumber::$numCard))){
            AjaxTool::returnJsonData(400, "请选择正确外显号码");
        }

        $idArr =  explode(",",$ids);
        if(!empty($idArr)){
            foreach ($idArr as $k=>$v){
                Module_Mediate_Workernumber::getInstance()->singleUpdate(['outNumber' => $callNum, 'id' => $v]);
            }
        }
        Lib_Redis_String::delKey('WORK_OUT_NUM');
        AjaxTool::returnJsonData(200, "操作成功");
    }


    //下载文件模板
    public function downTemplateAction()
    {
        $paramList[] = array(
            1 => '8888',
            2 => '2208510641',
            4 => 'pwd123456',
        );
        $header=['坐席号','分机号','分机密码'];
        Lib_XlsxExport::getInstance()->downExcel($paramList, $header,'坐席导入模板');
        exit;
    }
    public function updateAction(){

        if ($this->getRequest()->getPost()) {
            $data = $this->getRequest()->getPost('data', '');
            parse_str(urldecode($data),$data);
            $file = $this->getRequest()->getFiles('file');
            if(!empty($file)){
                $img_url = '';
                if ($file['error'] != 4) {
                    $uploadFile = Lib_Upload::getInstance()->uploadFile($file, 'caseupload');
                    if (!$uploadFile || $uploadFile['code']) {
                        AjaxTool::returnJsonData(405,'上传失败');
                    }
                    $img_url = $uploadFile['data'];
                }
                $url = realpath(LIBRARY_DIR . '/../') . '/resource' . $img_url;
                $file_info = pathinfo($url);
                if ($file_info && strtolower($file_info['extension']) == 'csv') {
                    $res = array_map('str_getcsv', file($url));
                    if ($res) {
                        unset($res[0]);
                    }
                } else {
                    try {
                        $res = Lib_XlsxRead::getInstance()->execute($url,1);
                    } catch (Exception $e) {
                        AjaxTool::returnJsonData(406,'文件格式不对'.$e);
                    }
                    if (empty($res)) {
                        AjaxTool::returnJsonData(407,'未发现数据');
                    }
                }
//                Func_Log::write("test11", '$res' , var_export($res, true));
                $header = $res[1];
                unset($res[1]);
                if (!$res) {
                    AjaxTool::returnJsonData(408, "未发现数据");
                }
                if(empty($header)){
                    AjaxTool::returnJsonData(409, "未发现表格表头");
                }
                if (!empty($res)) {
                    $success = 0;
                    $fail = 0;
                    foreach ($res as $k => $v) {
                        if(empty($v[0]) || empty($v[1]) || empty($v[2])){
                            $fail ++;
                            continue;
                        }
                        $arr = [
                            'workerId' => $v[0],
                            'extnumber' => $v[1],
                            'extnumberPswd' => $v[2],
                        ];
                        try {
                            $res = Module_Mediate_Workernumber::getInstance()->singleUpdate($arr,'workerId');
                            if ($res){
                                $success++;
                                continue;
                            }else{
                                $fail ++;
                                continue;
                            }
                        } catch (Exception $e) {
                            $fail ++;
                            continue;
                        }
                    }
                }
                AjaxTool::returnJsonData(200, "更新 {$success}个,失败 {$fail}个");

            }
        }
        if(empty($res)){
            AjaxTool::returnJsonData(500, "未检测到添加数据");
        }
        AjaxTool::returnJsonData(200, "操作成功");
    }

}
